package com.hsource.doctorcenter.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hsource.common.utils.CommonResp;
import com.hsource.common.utils.resultUtils.controller.BaseController;
import com.hsource.doctorcenter.domain.doctor.Doctor;
import com.hsource.doctorcenter.domain.user.UserBase;
import com.hsource.doctorcenter.feign.UserFeignClient;
import com.hsource.doctorcenter.service.api.IApiService;
import com.hsource.doctorcenter.service.doctor.IDoctorService;
import com.hsource.doctorcenter.service.file.IFileService;
import com.hsource.doctorcenter.service.problem.ProblemService;
import com.hsource.doctorcenter.util.RedisKeyUtil;
import com.hsource.doctorcenter.util.RedisUtil;
import com.hsource.doctorcenter.util.StaticValue;
import com.hsource.doctorcenter.util.StringUtils;
import com.hsource.doctorcenter.webSocket.WebSocketUtil;
import javazoom.jl.decoder.Bitstream;
import javazoom.jl.decoder.BitstreamException;
import javazoom.jl.decoder.Header;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.util.*;

/**
 * @author yangYang
 * @version 1.0
 * @date 2020/9/25 15:13
 * @describe 问题控制层
 */
@Slf4j
@Controller
@RequestMapping("problem")
public class ProblemController extends BaseController {
    @Autowired
    private IApiService apiService;
    @Autowired
    private IFileService fileService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ProblemService problemService;

    /**
     * 问题详情
     * @param userId 用户id
     * @param problemId 问题id
     * @return
     * @throws ParseException
     * @throws NoSuchAlgorithmException
     */
    @PostMapping("getProblemDetail")
    @ResponseBody
    public CommonResp getProblemDetail(String userId,String problemId) throws ParseException, NoSuchAlgorithmException {
        List<LinkedHashMap<String, String>> problemDetailList = problemService.getProblemDetailRedis(userId, problemId);
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("messages",problemDetailList);
        resultMap.put("doctorDetailPageUrl","https://api.bencaoyuantang.com/doctorDetailed/doctordetails.html");
        return success(resultMap);
    }

    /**
     * 读取语音的时长
     * @param fileUrl
     * @return
     * @throws MalformedURLException
     */
    public static int getDuration(String fileUrl) throws MalformedURLException {
        URL url = new URL(fileUrl);
        URLConnection con = null;
        try {
            con = url.openConnection();
            BufferedInputStream bis = new BufferedInputStream(con.getInputStream());
            Bitstream bt = new Bitstream(bis);
            //获取mp3时间长度
            Header header = bt.readFrame();
            int mp3Length = con.getContentLength();
            int time = (int) header.total_ms(mp3Length) / 1000;
            return time;
        } catch (BitstreamException e) {
            log.error(e.getMessage());
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return 0;
    }
        /**
     * 我的提问历史
     * @param userId 用户Id
     * @param startNum 开始数 用于支持翻页功能,从 0 开始计数
     * @param count 每次取的问题数 最大值200
     * @return
     * @throws ParseException
     * @throws NoSuchAlgorithmException
     */
    @PostMapping("getHistoricalQuestions")
    @ResponseBody
    public CommonResp getHistoricalQuestions(String userId,Integer startNum,Integer count,String type) throws ParseException, NoSuchAlgorithmException {
        Map<String, Object> historicalQuestions = problemService.getHistoricalQuestions(userId, startNum, count, type);
        historicalQuestions.put("userId",userId);
        return success(historicalQuestions);
    }


    /**
     * 快速提问提交图文
     * @param request 请求
     * @param contentString 文字提问内容
     * @param userId 用户id
     * @return
     * @throws IOException
     */
    @PostMapping("cacheProblemImageText")
    @ResponseBody
    public CommonResp cacheProblemInfo(MultipartHttpServletRequest request,String contentString,String userId) throws IOException {
        if(StringUtils.isBlank(contentString)||contentString.length()<10){
            return failed("问题描述不能少于10个字");
        }
        Map<String, Object> stringObjectMap = fileService.uploadOssFile(request);
        if(stringObjectMap.get("error").equals("0")) {
            List<String> images = (List<String>) stringObjectMap.get("files");
            String redisKeyString = RedisKeyUtil.getRedisKeyString(userId, RedisKeyUtil.IMAGE_TEXT_PROBLEM);
            redisUtil.set(redisKeyString, StaticValue.getContent(images, contentString));
            redisUtil.expire(redisKeyString, 10800);
            return success();
        }else{
            return failed(stringObjectMap.get("error_msg").toString());
        }
    }
}
